package com.ying.user.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ying.common.entity.Response;
import com.ying.common.entity.ResponseCode;
import com.ying.common.exception.BaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Response 通用工具类
 */
public class ResponseUtils {

    private static final Logger logger = LoggerFactory.getLogger(ResponseUtils.class);

    /**
     * 往 response 写出 json
     *
     * @param response       响应
     * @param responseCode   状态
     * @param data           返回数据
     */
    public static void renderJson(HttpServletResponse response, ResponseCode responseCode, Object data) {
        try {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(200);

            // FIXME: hutool 的 BUG：JSONUtil.toJsonStr()
            //  将JSON转为String的时候，忽略null值的时候转成的String存在错误
            response.getWriter()
                    .write(JSONUtil.toJsonStr(new JSONObject(new Response().userLoginDefined(responseCode, data), false)));
        } catch (IOException e) {
            logger.error("Response写出JSON异常，", e);
        }
    }

    /**
     * 往 response 写出 json
     *
     * @param response  响应
     * @param exception 异常
     */
    public static void renderJson(HttpServletResponse response, BaseException exception) {
        try {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(200);

            // FIXME: hutool 的 BUG：JSONUtil.toJsonStr()
            //  将JSON转为String的时候，忽略null值的时候转成的String存在错误
            response.getWriter()
                    .write(JSONUtil.toJsonStr(new JSONObject(new Response().exception(exception), false)));
        } catch (IOException e) {
            logger.error("Response写出JSON异常，", e);
        }
    }
}